﻿using Smart.Model;
using UnityEngine;
using UnityEngine.UI;

public class UIRender : MonoBehaviour
{
    [SerializeField]
    protected Material mMaterial;
    [SerializeField]
    protected Shader mShader;
    [SerializeField]
    protected Texture mTexture;

    public Material Material
    {
        get
        {
            if (null == mMaterial)
            {
                if (null == mShader)
                {
                    mShader = Shader.Find("Unlit/Transparent Colored");
                }

                if (null != mShader)
                    mMaterial = new Material(mShader);
            }
            return mMaterial;
        }
    }

    public Texture MainTexture
    {
        get
        {
            if(null != mTexture)
                return mTexture;

            if (null != mMaterial)
                return mMaterial.mainTexture;

            return null;
        }
        set
        {
            mTexture = value;
        }
    }

    MeshFilter mMeshFilter;
    Mesh mMesh;
    MeshRenderer meshRenderer;
    Buffer mBuffer;

    protected int[] triangles = new int[]
    {
        0,1,2,2,3,0
    };

    private void Awake()
    {
        mMeshFilter = gameObject.AddComponent<MeshFilter>();
        mMesh = new Mesh();
        mMesh.hideFlags = HideFlags.DontSave;
        meshRenderer = gameObject.AddComponent<MeshRenderer>();
    }

    private void Start()
    {
        Draw();
    }

    private void Draw()
    {
        var mat = Material;
        if (null == mat)
            return;

        var texture = MainTexture;
        if (null == texture)
            return;

        mat.mainTexture = texture;
        meshRenderer.material = mat;

        mMesh.Clear();
        mBuffer = mBuffer.Get(16);
        mBuffer.DrawRect(0, 0, 0, 1, 1);
        mBuffer.DrawUVRect(0, 0, 0, 1, 1);
        mMesh.vertices = mBuffer.buffer;
        mMesh.uv = mBuffer.uvs;
        mMesh.triangles = triangles;
        mMeshFilter.mesh = mMesh;
    }
}